package com.mxpioframework.security.policy;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;

import com.mxpioframework.common.util.BeanReflectionUtils;
import com.mxpioframework.common.util.SpringUtil;
import com.mxpioframework.jpa.policy.impl.AbstractGeneratorPolicy;
import com.mxpioframework.jpa.policy.impl.CrudType;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;

/**
 * 基于redis的序列生成器
 * 
 * @author yinyf
 *
 */
public class SequencePolicy extends AbstractGeneratorPolicy {
	@Override
	public CrudType getType() {
		return CrudType.SAVE;
	}

	@Override
	protected Object getValue(Object entity, String field) {
		Object value = BeanReflectionUtils.getPropertyValue(entity, field);
		if ("".equals(value)) {
			value = null;
		}
		if (value == null) {
			RedisTemplate<String, Object> redisTemplate = SpringUtil.getBean("redisTemplate");
			String key = "SEQ:" + field.toUpperCase();
			int seqValue = 1;
			if (redisTemplate.hasKey(key)) {
				seqValue = NumberUtil.parseInt(String.valueOf(redisTemplate.opsForValue().increment(key)));
			} else {
				DateTime beginOfDate = DateUtil.beginOfDay(DateUtil.offsetDay(DateTime.now(), 1));
				long diffSecond = DateUtil.between(DateTime.now().toJdkDate(), beginOfDate.toJdkDate(),
						DateUnit.SECOND);
				redisTemplate.opsForValue().set(key, seqValue, diffSecond, TimeUnit.SECONDS);
			}
			value = field.toUpperCase() + DatePattern.PURE_DATE_FORMAT.format(DateTime.now())
					+ NumberUtil.decimalFormat("000000", seqValue);
		}
		return value;
	}

}
